var util = require('../../utils/util.js');
var ajax = require('../../utils/ajax.js');
var common = require('../../utils/common.js');
var PageBase = require('../../common/PageBase.js');
var app = getApp();

Page(common.extendPage(PageBase, {
  data: {
    iconSize: 18,
    iconColor: '#FF8657',
    iconType: 'success',
    orderId: 0,
    orderNum: '',
    payPrice: 0,
    cid: ''
  },
  /**
   * 页面初始化
   */
  onLoad(options) {
    this._options = options;
    this.setData({
      orderNum: this._options.ordernum,
      payPrice: parseFloat(this._options.amount).toFixed(2),
      orderId: this._options.orderId,
      cid: this._options.cid || ''
    })
  },
  /**
   * 订单支付
   */
  _orderPay(evt) {
    var paramsUrl = '/public/api/orders/payOrder';
    var {
      orderNum,
      payPrice,
      orderId,
      cid
    } = this.data;
    var paramsData = {
      cid,
      oid: this.data.orderId,
      uid: wx.getStorageSync('uid'),
      paytype: 'wxpay_a',
      openid: app.getOpenId()
    }
    ajax.P({
      url: paramsUrl,
      data: paramsData,
      success: (res) => {
        console.log(res);
        const {
          timeStamp,
          nonceStr,
          signType,
          paySign
        } = res.payinfo;

        const packageStr = res.payinfo.package;
        wx.requestPayment({
          'timeStamp': timeStamp.toString(),
          'nonceStr': nonceStr,
          'package': packageStr,
          'signType': signType,
          'paySign': paySign,
          success(res) {
            util.tips('支付成功', () => {
              wx.redirectTo({
                url: '/pages/payResult/index?orderId=' + orderId + '&payPrice=' + payPrice + '&orderNum=' + orderNum,
              })
            })
          },
          fail(res) {
            util.tips('支付失败', () => {
              wx.hideLoading();
            })
          }
        })
      }
    })
  }
}));